package com.zhang.filter;

import com.zhang.Token.JwtToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class JwtFilter extends BasicHttpAuthenticationFilter {

    private final String ACCESS_TOKEN_HEADER = "Access-Token";



    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            executeLogin(request,response);
            return true;
        } catch (Exception e){
//            throw new AuthenticationException("Token失效，请重新登录:"+e.getMessage());
            //都应该返回true有些类似于登录注册的功能请求是不可能携带jwtToken
            return true;
        }
    }


    /**
     * @see com.zhang.realm.DBRealm
     */
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception{
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(ACCESS_TOKEN_HEADER);

        JwtToken jwtToken = new JwtToken(null);
        if (StringUtils.hasLength(token)){
            //生成jwtToken（AuthenticationToken）
            jwtToken.setToken(token);
        }
        //交给DBRealm去验证
        getSubject(request,response).login(jwtToken);

        return true;
    }
}
